package com.aihongbo.service

import android.app.Service
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.Message
import android.os.Messenger
import android.util.Log

class AihongboService : Service() {

    private val MSG_GPT = 0x000
    private val MSG_SUM: Int = 0x110

    override fun onBind(intent: Intent?): IBinder? {
        return messenger.binder
    }

    val statusHandle = object : Handler() {
        override fun handleMessage(msg: Message) {
            Log.d("aihongbo", "=======>${msg.what}")
        }
    }

    override fun onCreate() {
        super.onCreate()
        Thread(Runnable {
            while (true) {
                statusHandle.sendEmptyMessage(1)
                Thread.sleep(1000)
            }
        }).start()
    }

    private val messenger = Messenger(object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            val toMessage = Message.obtain(msg)
            Log.d("GPT", "收到消息${msg}")
            when (msg.what) {
                MSG_GPT -> {
                    toMessage.data = Bundle().apply {
                        putString(
                            "data", "GPT你好"
                        )
                    }
                    msg.replyTo.send(toMessage)
                }

                MSG_SUM -> {
                    toMessage.data = Bundle().apply {
                        putString(
                            "data", "计算${msg.arg1}和${msg.arg2}之和为${msg.arg1 + msg.arg2}"
                        )
                    }
                    toMessage.arg2 = msg.arg1 + msg.arg2
                    msg.replyTo.send(toMessage)
                }
            }
            super.handleMessage(msg)
        }
    })
}